//go:generate goversioninfo -icon=favicon.ico

package main

import (
	"encoding/json"
	"fmt"
	"github.com/rivo/tview"
	"io"
	"net/http"
	"os"
	"time"
)

func main() {
	application := tview.NewApplication()

	textView := tview.NewTextView().SetDynamicColors(true).
		SetRegions(true).
		SetChangedFunc(func() {
			application.Draw()
		})
	textView.SetBorder(true).SetTitle("Right (20 cols)")

	flex := tview.NewFlex().
		AddItem(tview.NewBox().SetBorder(true).SetTitle("Left (1/2 x width of Top)"), 0, 1, false).
		AddItem(tview.NewFlex().SetDirection(tview.FlexRow).
			AddItem(tview.NewBox().SetBorder(true).SetTitle("Top"), 0, 1, false).
			AddItem(tview.NewBox().SetBorder(true).SetTitle("Middle (3 x height of Top)"), 0, 3, false).
			AddItem(tview.NewBox().SetBorder(true).SetTitle("Bottom (5 rows)"), 5, 1, false), 0, 2, false).
		AddItem(textView, 20, 1, false)

	application.SetRoot(flex, true).SetFocus(flex)

	go func() {
		if err := application.Run(); err != nil {
			panic(err)
		}
	}()

	mainJsonByte := getHttp("https://gitee.com/sisyphus2016/ua-tcg-info/raw/master/main.json")

	mainJson := MainJson{}
	json.Unmarshal(mainJsonByte, &mainJson)

	{
		localMainJson, _ := os.Open("./main.json")
		localMainJsonByte, err := io.ReadAll(localMainJson)
		if err != nil {
			fmt.Fprintf(textView, "%s ", "if1")

			os.WriteFile("./main.json", mainJsonByte, 0644)
			downloadMain()
		} else {
			fmt.Fprintf(textView, "%s ", "if2")

			localMainJson := MainJson{}
			json.Unmarshal(localMainJsonByte, &localMainJson)

			if localMainJson.Version < mainJson.Version {
				os.WriteFile("./main.json", mainJsonByte, 0644)
				downloadMain()
			}
		}
	}

	for {
		time.Sleep(10 * time.Second)
	}
}

func downloadMain() {
	fileByte := getHttp("https://gitee.com/sisyphus2016/ua-tcg-info/raw/master/UA%E5%B7%A5%E5%85%B7%E7%AE%B1.exe")
	os.WriteFile("./UA工具箱.exe", fileByte, 0644)
}

func getHttp(url string) []byte {
	resp, err := http.Get(url)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	body, _ := io.ReadAll(resp.Body)
	return body

}

type MainJson struct {
	Version int `json:"version"`
}
